package com.gavin.sample.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class DesUtil {
	public static final String DES = "DES";
	
	public static String genKeyDES() throws Exception {
		KeyGenerator keyGen = KeyGenerator.getInstance(DES);
		keyGen.init(56);
		SecretKey key = keyGen.generateKey();
		String base64Str = Base64.encodeBase64String(key.getEncoded());
		return base64Str;
	}
	
	public static SecretKey loadKeyDES(String base64Key) {
		byte[] bytes = Base64.decodeBase64(base64Key);
		SecretKey key = new SecretKeySpec(bytes, DES);
		return key;
	}
	
	public static byte[] encryptDES(byte[] source, SecretKey key) throws Exception {
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] bytes = cipher.doFinal(source);
		return bytes;
	}
	
	public static byte[] decryptDES(byte[] sources, SecretKey key) throws Exception {
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] bytes = cipher.doFinal(sources);
		return bytes;
	}
	
	public static void main(String[] args) {
		try {
			String keyDes = genKeyDES();
			System.out.println("DES key:" + keyDes);
			SecretKey secretKey = loadKeyDES(keyDes);
			
			String str = "hi,i'm gavin";
			System.out.println("the string is " + str);
			byte[] encryptBytes = encryptDES(str.getBytes("UTF-8"), secretKey);
			String encryptStr = Base64.encodeBase64String(encryptBytes);
			System.out.println("the string after encrypt by DES is " + encryptStr);
			byte[] decryptBytes = decryptDES(Base64.decodeBase64(encryptStr), secretKey);
			String decryptStr = new String(decryptBytes, "UTF-8");
			System.out.println("the string after decrypt by DES is " + decryptStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
